<?php
/**
 *    财务退款管理控制器
 */
class Financial_refundApp extends BackendApp
{
    protected $_financial_refund_mod;

    function __construct()
    {
        $this->Financial_refund_settingApp();
    }

    function Financial_refund_settingApp()
    {
        parent::BackendApp();
        $this->_financial_refund_mod =& m('financial_refund');
    }

    function index(){
        $page = $this->_get_page();
        $conditions = $this->_get_query_conditions(array(
            array(
                'field' => 'RefundStatus',
                'equal' => '=',
                'type'  => 'numeric',
            ),array(
                'field' => 'create_time',
                'name'  => 'add_time_from',
                'equal' => '>=',
                'handler'=> 'gmstr2time',
            ),array(
                'field' => 'create_time',
                'name'  => 'add_time_to',
                'equal' => '<=',
                'handler'   => 'gmstr2time_end',
            )
        ));

        //搜索关键字
        if($_GET['sn']){
            $sn = trim($_GET['sn']);
            $conditions .= " AND (PaymentNo like "."'%$sn%'"." OR OrderNo like "."'%$sn%'"." OR refund_sn like "."'%$sn%'".")";
            $this->assign('sn',$sn);
        }
        $res = $this->_financial_refund_mod->find(array(
            'conditions'    => '1=1 ' . $conditions,
            'limit' => $page['limit'],
            'count' => true,
            'order' => "create_time desc"
        )); //找出所有商城的合作伙伴
        foreach($res as $k=>$v){
            $str = explode(',',$v['PaymentNo']);
            if(count($str) > 1){
                $res[$k]['strPaymentNo'] = $str[0].'<br/>'.$str[1];
            }else{
                $res[$k]['strPaymentNo'] = $v['PaymentNo'];
            }
        }
        $page['item_count'] = $this->_financial_refund_mod->getCount();   //获取统计的数据
        $this->_format_page($page);
        $this->assign('res', $res);
        $this->assign('filtered', $conditions? 1 : 0); //是否有查询条件
        $page['item_count'] = $this->_financial_refund_mod->getCount();
        $this->import_resource(array('script' => 'mlselection.js,inline_edit.js'));
        $this->_format_page($page);
        $this->assign('order_status_list', array(
            FINANCIAL_REFUND_DISPOSAL => '待确认',
            FINANCIAL_REFUND_PENDING => '待财务处理',
            FINANCIAL_REFUND_ING => '待退款',
            FINANCIAL_REFUND_FINISH => '已退款',
        ));
        $this->assign('page_info', $page);
        $this->import_resource(array('script' => 'inline_edit.js,jquery.ui/jquery.ui.js,jquery.ui/i18n/' . i18n_code() . '.js',
            'style'=> 'jquery.ui/themes/ui-lightness/jquery.ui.css'));
        $this->display('financial_refund.index.html');
    }

    /**请求OMS查询退款进度接口*/
    public function searchRefund(){
        $OrderNo = $_GET['OrderNo'];
        $id = $_GET['id'];
        if(!$OrderNo || !$id){
            $this->show_warning('信息传输错误');
            return;
        }
        $refund_array[0] = array(
            'OrderNo' => $OrderNo
        );
        $result = $this->common_finance($refund_array);
        $this->show_warning($result['msg']);
    }
    //公共方法
    private function common_finance($refund_array){
        $send_array = array(
            'ClientGuid' => CLIENT_GUID,
            'ClientName' => CLIENT_NAME,
            'Order' => $refund_array
        );
        $url = API_URL.'/api/order/QueryRefundStatus';
        $rs = $this->sync_data($url, $send_array);

        if(!$rs || $rs['code'] != '200'){
            return $rs['msg'];
        }else{
            $order_sn = '';
            if($rs['success'] != true) {
                return $rs['msg'];
            }else{
                $arr['code'] = 1;
                //查询OMS是否可退款接口  1可退 0不可退
                if(!empty($rs['data'])){
                    $refundDataResult = $rs['data'];
                    foreach($refundDataResult as $key=>$value){
                        if($value['AllowedRefund'] == 1){
                            if($order_sn){
                                $order_sn .= ','.$value['OrderNo'];
                            }else{
                                $order_sn .= $value['OrderNo'];
                            }
                        }
                    }
                }else{
                    $arr['msg'] = 'oms返回参数有误';
                }

                if($order_sn){
                    $conditions = "OrderNo IN (".$order_sn.")";
                    $info = $this->_financial_refund_mod->find(array('conditions'=>$conditions));
                    if(!empty($info)){
                        //查询OMS可退款，将财务退款单编程可退款状态，退款订单状态改为仓库已确认可以退款   WAREHOUSE_CONFIRMED
                        foreach($info as $k=>$v){
                            $refundInfo = &m('refund')->get(array('conditions'=>'refund_sn = '.$v['refund_sn']));
                            if($refundInfo){
                                $refundData['status'] = 'WAREHOUSE_CONFIRMED';
                                $save = &m('refund')->edit($refundInfo['refund_id'],$refundData);
                                $saveData['RefundStatus'] = 201;
                                $saveData['IsEnabled'] = 1;
                                $this->_financial_refund_mod->edit($v['id'],$saveData);
                                $arr['msg'] = '仓库审核已通过，已提交到财务处理';
                            }else{
                                $arr['msg'] = '查询退款订单失败1';
                            }
                        }
                    }else{
                        $arr['msg'] = '财务退款信息不存在';
                    }
                }else{
                    $arr['msg'] = '仓库审核未通过，暂时不可退款';
                }
            }
            return $arr;
        }
    }

    //批量提交到财务
    public function batch_finance(){
        $id = isset($_GET['id']) ? trim($_GET['id']) : '';
        if(!$id){
            $this->show_warning('您没有勾选信息！');
            return ;
        }
        $conditions = "id IN (".$id.")";
        $list = $this->_financial_refund_mod->find(array('conditions'=>$conditions));
        $arr = array_values($list);
        $num = 0;
        foreach($arr as $k=>$v){
            //查询符合条件的拼接参数并调取oms接口
            if($v['RefundStatus'] == 200){
                $newArr[$num]['OrderNo'] = $v['OrderNo'];
                $num ++ ;
            }else{
                continue;
            }
        }
        if($num > 0){
            $result = $this->common_finance($newArr);
            $this->show_warning($result['msg']);
            return ;
        }else{
            $this->show_warning('您勾选的信息，不符合当前操作！');
            return ;
        }
    }
    //退款到原支付账号
    public function refund_post(){
        $refund_sn = $_GET['refund_sn'];
        $msg = '信息传输错误';
        if($refund_sn){
            $refundModel = &m('refund');
            $orderModel = &m("order");
            $wishModel = &m('wish');
            $memberModel = &m('member');

            $wishPayLogModel = &m('wish_pay_log');
            $msg = '财务退款单信息错误';
            $financialRefundInfo = $this->_financial_refund_mod->get(array('conditions'=>'refund_sn = '.$refund_sn));
            if($financialRefundInfo){
                $refundInfo = $refundModel->get(array('conditions'=>'refund_sn = '.$refund_sn));
                $msg = '退款信息不存在';
                if($refundInfo){
                    $orderInfo = $orderModel->get(array('conditions'=>'order_sn = '.$financialRefundInfo['OrderNo']));

                    //查询订单是否为心愿单成交订单  如是心愿单成交订单，或许需要退款两笔金额
                    if($orderInfo['type'] == 'wishOrder'){
                        //心愿单订单退款：查看付款记录是否有两笔
                        $wishInfo = $wishModel->get(array("conditions"=>"order_id = ".$orderInfo['order_id']));

                        if(empty($wishInfo)){
                            $msg = '心愿单信息不存在';
                            $this->show_warning($msg);
                        }
//                        if($wishInfo['state'] != 3) {
//                            $msg = '心愿单状态不符合当前操作';
//                            $this->show_warning($msg);
//                        }
                        $wishPayLogInfo = $wishPayLogModel->find(array("conditions"=>"wish_id = ".$wishInfo['id']));
                        if(empty($wishPayLogInfo)) {
                            $msg = '心愿单付款记录有误';
                            $this->show_warning($msg);
                        }
                        foreach($wishPayLogInfo as $k=>$v){
                            $paymentCode = 'wxpay_app';
                            if($v['pay_type'] == 2){
                                $paymentCode = 'alipay_app';
                            }
                            //查询首款 + 尾款 付款记录并进行退款操作！
                            if($v['type'] == 1){
                                $data = array(
                                    'order_sn' => $v['order_sn'],
                                    'total_fee' => $v['money'],
                                    'payment_code' => $paymentCode,
                                    'refund_sn' => $refundInfo['refund_sn']
                                );
                                $memberModel->writeLog('心愿单退款标识：首款的心愿单付款记录'.json_encode($v));
                                $result1 = $refundModel->refundSign($data);
                                $memberModel->writeLog('心愿单退款标识：首款的心愿单退款结果'.json_encode($result1));
                                $msg = $this->refundAfter($orderInfo,$refundInfo,$financialRefundInfo,$result1,$paymentCode);
                            }
                            if($v['type'] == 2){
                                $data2 = array(
                                    'order_sn' => $v['order_sn'],
                                    'total_fee' => $v['money'],
                                    'payment_code' => $paymentCode,
                                    'refund_sn' => $refundInfo['refund_sn']
                                );
                                $memberModel->writeLog('心愿单退款标识：尾款的心愿单付款记录'.json_encode($v));
                                $result2 = $refundModel->refundSign($data2);
                                $memberModel->writeLog('心愿单退款标识：尾款的心愿单退款结果'.json_encode($result2));
                                $msg = $this->refundAfter($orderInfo,$refundInfo,$financialRefundInfo,$result2,$paymentCode);
                            }
                        }
                    }else{
                        //普通订单退款   拼接退款参数
                        $data = array(
                            'order_sn' => $orderInfo['order_sn'],
                            'total_fee' => $financialRefundInfo['Total'],
                            'payment_code' => $orderInfo['payment_code'],
                            'refund_sn' => $refundInfo['refund_sn']
                        );
                        $result = $refundModel->refundSign($data);
                        $memberModel->writeLog('接收订单退款接口结果：'.json_encode($result));
                        $order_type = $orderInfo['payment_code'];
                        $msg = $this->refundAfter($orderInfo,$refundInfo,$financialRefundInfo,$result,$order_type);
                    }
                    //查看是否使用优惠券，如使用优惠券，将优惠券退回到原支付账号
                    if($orderInfo['coupon_id']){
                        $this->checkCoupon($orderInfo);
                    }

                }
            }
        }
        $memberInfo = $memberModel->get(array('conditions'=>"user_id = ".$orderInfo['buyer_id']));
        if($memberInfo['fourth_class']){
            $parentInfo = $memberModel->get(array('conditions'=>"user_id = ".$memberInfo['fourth_class']));
            if($parentInfo['is_promoters'] == 1){
                $commission_dj['commission'] = $parentInfo['commission'] - $orderInfo['commission_amount'];
                $saveParentMember = $memberModel->edit($parentInfo['user_id'],$commission_dj);

                $saveOrder = $orderModel->edit($orderInfo['order_id'],array('is_change'=>1));
                $time = time();
                //查询订单商品信息
                $orderGoods = &m("order_goods")->get(array("conditions"=>"order_id = ".$orderInfo['order_id']));
                //查询商品信息
                $goodsSpecInfo = &m("goods_spec")->get(array("conditions"=>"spec_id = ".$orderGoods['spec_id']));
                //查询店铺信息
                $storeInfo = &m("store")->get(array("conditions"=>"store_id = ".$parentInfo['user_id']));
                //查询配置信息
                $mallConfigInfo = &m("mall_config")->get(array("conditions"=>"code = promotion_proportion"));


                //加入到佣金退还详情表
                $addDetailData = array(
                    'order_id'              => $orderInfo['order_id'],
                    'user_id'               => $parentInfo['user_id'],
                    'order_sn'              => $orderInfo['order_sn'],
                    'order_pay_time'        => $orderInfo['pay_time'],
                    'order_finish_time'     => $time,
                    'commission_finish_time'=> $time,
                    'account_calibration_time'=> $time,
                    'goods_id'              => $orderGoods['goods_id'],
                    'spec_id'               => $orderGoods['spec_id'],
                    'goods_name'            => $orderGoods['goods_name'],
                    'sku'                   => $goodsSpecInfo['sku'],
                    'num'                   => $orderGoods['quantity'],
                    'price'                 => $orderGoods['price'],
                    'price_amount'          => $orderInfo['order_amount'],
                    'sign'                  => '-',
                    'commission_proportion' => $mallConfigInfo['value'],
                    'commission'            => $orderInfo['commission_amount'],
                    'stock_style'           => $goodsSpecInfo['spec_3'],
                    'user_name'             => $parentInfo['user_name'],
                    'serial_number'         => $storeInfo['serial_number']
                );
                $memberModel->writeLog('佣金订单退款：组合退款佣金的信息'.json_encode($addDetailData));
                $addDetailOp = &m("commission_detail")->add($addDetailData);
                //加入到佣金退还记录表
                $addLogData = array(
                    'user_id'  => $parentInfo['user_id'],
                    'fans_id'  => $orderInfo['buyer_id'],
                    'sign'     => '-',
                    'order_id' => $orderInfo['order_id'],
                    'order_money' => $orderInfo['order_amount'],
                    'commission_money' => $orderInfo['commission_amount'],
                    'finish_time'  => $time,
                );
                $addlog = &m("commission_log")->add($addLogData);




            }
        }
        $arr['msg'] = $msg;
        $this->show_warning($arr['msg']);
        return;
    }
    //退款后处理逻辑
    function refundAfter($orderInfo,$refundInfo,$financialRefundInfo,$result,$order_type='ali_pay'){
        $orderModel = &m('order');
        $refundModel = &m('refund');
        $memberModel = &m('member');

        //判断订单是普通订单还是心愿单  wishOrder：心愿单 material：普通订单
        $orderType = 10;
        if($orderInfo['type'] == 'wishOrder'){
            $orderType = 20;
        }
        $return_arr = array();
        $msg = '';
        if($order_type == 'epaywxnative' || $order_type == 'wxpay_app' || $order_type == 'jspay_app'){
            if($result['result_code'] == 'SUCCESS' && $result['return_code'] == 'SUCCESS'){
                //修改退款单状态
                $findData['RefundStatus'] = 300;
                $this->_financial_refund_mod->edit($financialRefundInfo['id'],$findData);
                //修改订单状态为退款成功
                $orderData['status'] = 50;
                $saveOrderStatus = $orderModel->edit($orderInfo['order_id'],$orderData);
                //修改退款订单退款成功
                $refundData['status'] = 'SUCCESS';
                $saveRefundStatus = $refundModel->edit($refundInfo['refund_id'],$refundData);

                $msg = '微信退款成功';

                //新增推送到oms退款接口   API/Order/OrderRefund
                $return_arr = array(
                    'ClientGuid'   => CLIENT_GUID,                      //注册系统Id
                    'ClientName'   => CLIENT_NAME,                      //注册系统名称
                    'BillNo'       => $financialRefundInfo['OrderNo'],  //单据编号
                    'BillType'     => $orderType,                       //单据类型
                    'PayName'      =>  '财付通支付科技有限公司',         //支付单位名称
                    'PayCode'      =>  '4403169D3W',                    //支付单位编号
                    'PayTransactionId' =>  $result['transaction_id'],   //微信订单号
                    'PayPrice'     => $financialRefundInfo['Total'],    //退款金额
                    'RefundNo'     => $financialRefundInfo['refund_sn'],//退款订单号
                );
            }else{
                $msg = $result['return_msg'];
            }
        }else if($order_type == 'epayalipay' || $order_type == 'alipay_app'){
            //支付宝
            if($result['alipay_trade_refund_response']['code'] == '10000'){
                //修改退款单状态
                $findData['RefundStatus'] = 300;
                $this->_financial_refund_mod->edit($financialRefundInfo['id'],$findData);
                //修改订单状态为退款成功
                $orderData['status'] = 50;
                $saveOrderStatus = $orderModel->edit($orderInfo['order_id'],$orderData);
                //修改退款订单退款成功
                $refundData['status'] = 'SUCCESS';
                $saveRefundStatus = $refundModel->edit($refundInfo['refund_id'],$refundData);
                $msg = '支付宝退款成功';

                //新增推送到oms退款接口   API/Order/OrderRefund
                $return_arr = array(
                    'ClientGuid'   => CLIENT_GUID,                      //注册系统Id
                    'ClientName'   => CLIENT_NAME,                      //注册系统名称
                    'BillNo'       => $financialRefundInfo['OrderNo'],  //单据编号
                    'BillType'     => $orderType,                       //单据类型
                    'PayName'      =>  '支付宝(中国)网络技术有限公司',    //支付单位名称
                    'PayCode'      =>  '31222699S7',                    //支付单位编号
                    'PayTransactionId' =>  $result['alipay_trade_refund_response']['trade_no'],         //微信订单号
                    'PayPrice'     => $financialRefundInfo['Total'],    //退款金额
                    'RefundNo'     => $financialRefundInfo['refund_sn'],//退款订单号
                );

            }else{
                $msg = $result['return_msg'];
            }
        }else{
            $msg = '未知的支付类型';
        }
        $url = API_URL.'/API/Order/OrderRefund';
        $rs = $this->sync_data($url, $return_arr);
        $memberModel->writeLog('退款订单请求oms地址：'.$url.'<br/> 请求数据'.json_encode($return_arr).' <br/> 请求结果'.json_encode($rs));
        if(!$rs || $rs['code'] != '200') {
            $msg = '退款成功：'.$rs['Message'];
        }
        return $msg;
    }


    //工具方法  查看订单信息中是否有使用过优惠券的情况
    function checkCoupon($orderInfo){
        $memberCoupon = &m("member_coupon");
        $member = &m("member");
        $order = &m("order");
        $info = $memberCoupon->get(array("conditions"=>"id = ".$orderInfo['coupon_id'].' AND user_id = '.$orderInfo['buyer_id']));
        if(!empty($info)){
            $saveData['is_used'] = 0;
            $saveData['use_time'] = 0;
            $save = $memberCoupon->edit($info['id'],$saveData);
            $saveOrder = $order->edit($orderInfo['order_id'],array("coupon_id"=>0));
            $member->writeLog('退款订单：'.$orderInfo['order_sn'].'<br/> 返回优惠券到原账户');
        }
    }



    /**curl OMS请求**/
    function sync_data($url, $data_string)
    {
        $data_string = json_encode($data_string);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // https请求 不验证证书和hosts
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json; charset=utf-8',
                'Content-Length: ' . strlen($data_string))
        );
        ob_start();
        $res = curl_exec($ch);
        if (!$res) {
            return false;
        } else {
            return json_decode($res,true);
        }
        return array('code' => $return_code, 'result' => $return_content);
    }
}